const fs = require("fs");
const path = require("path");
const cProcess = require("child_process");
const cwd = process.cwd();
const Tools = require("./tools.js");

const regs = {
  parseHosts: /(#*) *((\d+\.)+\d+) +(([a-zA-z][a-zA-z0-9]*\.)*[a-zA-z][a-zA-z0-9]*)/,
  parseLocalHosts: /#env-(?:.+)#/g,
  parseLocalHostsTest: /#env-(?:.+)#/,
  parseLocalHostsReplace: /(?:#env-)(.+)(?:#)/,
};
function isHosts(item) {
  return item && regs.parseHosts.test(item);
}
function parseHosts(item) {
  return item.replace(/\n+/, "\n").replace(/\r+/, "\n").split(/\n+/).map(item => parseHost(item));
}
function parseHost(item) {
  let ret = item;
  isHosts(item) && item.replace(regs.parseHosts, function () {
    const [meadingless, disabled, ip, meadingless1, name, ] = arguments;
    ret = {ip: ip, name: name, disabled: !!disabled};
  });
  return ret;
}

function stringifyHost(hosts){
  return hosts.filter(item => item).map(item => item.ip ? `${item.disabled ? `#` : ""} ${item.ip} ${item.name}` : item).join("\n");
}
function stringifyHosts(hostsList){
  return hostsList.map(item => `#env-${item.name}#\n${stringifyHost(item.content)}`).join("\n");
}
function parseLocalHosts(item){
  const names = item.match(regs.parseLocalHosts);
  const conts = item.split(regs.parseLocalHosts);
  conts.shift();
  const ret = [];
  names.forEach((item, index) => {
    ret.push({
      isEnv: regs.parseLocalHostsTest.test(item),
      name: item.replace(regs.parseLocalHostsReplace, "$1"),
      content: parseHosts(conts[index])
    })
  });
  return ret;
}

module.exports = function getTools(rootPath) {
  const type = require(path.join(rootPath, `sections/ctools/src/type.js`));
  const {cRequire} = Tools(rootPath);
  const confPath = `ctools.conf`;
  const confRootPath = path.join(rootPath, confPath);
  const localHostsPath = `c:\\windows\\system32\\drivers\\etc\\hosts`;
  const customHostsPath = path.join(rootPath, confPath, "hostsConf.txt");
  function setHosts(dto, cur) {
    fs.writeFileSync(customHostsPath, stringifyHosts(dto));
    fs.writeFileSync(localHostsPath, stringifyHosts([cur]));
  }
  function getHosts() {
    return {
      local: parseHosts(fs.readFileSync(localHostsPath, "utf-8")),
      custom: parseLocalHosts(fs.readFileSync(customHostsPath, "utf-8")),
    }
  }
  return {
    getHosts, setHosts
  }
};
